<template>
  <div id="main">
    <!--<div class="left">-->
      <!--<div class="nav-list-box">-->
        <!--<div class="nav-list-item" :class="active == index?'nav-list-item-active':''" v-for="(item,index) in navList"-->
             <!--:key="index" @click="getNav(item,index)">-->
          <!--{{ item.name }}-->
        <!--</div>-->
      <!--</div>-->
    <!--</div>-->
    <div class="content" id="playWnd">

    </div>
  </div>
</template>

<script>
function debounce(fn, interval) {  //防抖
  var timer
  var gapTime = interval || 1000
  return function () {
    clearTimeout(timer)
    var context = this
    let args = arguments[0]
    timer = setTimeout(function () {
      fn.call(context, ...arguments)
    }, gapTime)
  }
}

function throttle(fn, interval) {
  console.log(565656)
  var enterTime = 0
  var gapTime = interval || 300
  return function () {
    var context = this
    var backTime = new Date()
    if (backTime - enterTime > gapTime) {
      fn.call(context, ...arguments)
      enterTime = backTime
    }
  }
}


var oWebControl = null;
var bIE = (!!window.ActiveXObject || 'ActiveXObject' in window);// 是否为IE浏览器
var pubKey = '';                    // demo中未使用加密，可根据需求参照开发指南自行使用加密功能
var initCount = 0;
var playMode = 0;                   // 播放类型，0-预览，1-回放
var showDivInstruction = false;     // 标志是否显示使用说明弹框



export default {
  data() {
    return {
      indexCode:'',
      show_type:'2x2',
      navList: [
        {
          name: '大厅门',
          value: 'a7adfcd0ceb94561aac2b9c2c65f6331'
        },
        {
          name: '五楼通道西南角',
          value: 'dd2198817aaf4f83abfc36ce30e2e89d'
        },
        {
          name: '四楼通道西北角',
          value: 'c8ddecc12cd046f080bae316e86c59de'
        },
        {
          name: '四楼通道东北角',
          value: '6415dc72b0b64fbaad5292a47b9a2149'
        },
      ],
      active: -1,
      endTime : Math.floor(new Date(this.dateFormat(new Date(), "yyyy-MM-dd 23:59:59").replace('-', '/').replace('-', '/')).getTime() / 1000).toString(),
      startTime : Math.floor(new Date(this.dateFormat(new Date(), "yyyy-MM-dd 00:00:00").replace('-', '/').replace('-', '/')).getTime() / 1000).toString(),
      playTime : Math.floor(new Date(this.dateFormat(new Date(), "yyyy-MM-dd 00:00:00").replace('-', '/').replace('-', '/')).getTime() / 1000).toString(),
    }
  },
  watch: {},
  created() {

  },
  mounted() {
    window.addEventListener('message', this.handleMessage);
  },
  destroyed() {
  },
  beforeDestroy() {
    window.removeEventListener('message', this.handleMessage);
    if (oWebControl != null) {
      oWebControl.JS_HideWnd();  // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
      oWebControl.JS_Disconnect().then(function () {
      }, function () {
      });
    }
  },
  methods: {
    handleMessage(event) {
      if(event.data.code){
        this.indexCode = decodeURIComponent(event.data.code).split('@')[0];
        console.log(7777,this.indexCode)
        this.adaptation();
        this.initPlugin();
        window.addEventListener('resize', () => {
          if (oWebControl != null) {
          oWebControl.JS_Resize(800, 400);
          this.setWndCover();
        }
        this.adaptation();
      });
      }
    },
    getQueryParams(){
      var queryString = window.location.search;
      var urlParams = new URLSearchParams(queryString);
      var param1 = urlParams.get('code') || '34030300001310549008@3403030000';
      var param2 = urlParams.get('show_type') || '1x1';

      $http.get('api/index.php',{
        code: param1,
        show_type: param2,
      }).then(res => {
        if(res.code == 200){
          this.show_type = param2
          this.indexCode = res.data.indexCode;
          this.adaptation();
          this.initPlugin();
          window.addEventListener('resize', () => {
            if (oWebControl != null) {
              oWebControl.JS_Resize(800, 400);
              this.setWndCover();
            }
            this.adaptation();
          });
        }else {
          Toast(res.msg)
        }
      })
    },
    initPlugin() {
      let that = this;
      oWebControl = new WebControl({
        szPluginContainer: "playWnd",
        iServicePortStart: 15900,
        iServicePortEnd: 15900,
        szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11",   // 用于IE10使用ActiveX的clsid
        cbConnectSuccess: ()=> {
          initCount = 0;
          this.setCallbacks();
          oWebControl.JS_StartService("window", {
            dllPath: "./VideoPluginConnect.dll"
          }).then(()=> {
            oWebControl.JS_CreateWnd("playWnd", 800, 400).then(function () {
              console.log("JS_CreateWnd success");
              oWebControl.JS_RequestInterface({
                funcName: "getRSAPubKey",
                argument: JSON.stringify({
                  keyLength: 1024
                })
              }).then((oData)=> {
                console.log(oData)
                that.init();
                if (oData.responseMsg.data) {
                  pubKey = oData.responseMsg.data


                }
              });
            });
          }, function () {

          });
        },
        cbConnectError: ()=>{
          console.log("cbConnectError");
          oWebControl = null;
          $("#playWnd").html("插件未启动，正在尝试启动，请稍候...");
          WebControl.JS_WakeUp("VideoWebPlugin://");
          initCount++;
          if (initCount < 3) {
            setTimeout( ()=> {
              this.initPlugin();
            }, 3000)
          } else {
            $("#playWnd").html("插件启动失败，请检查插件是否安装！");
          }
        },
        cbConnectClose: (bNormalClose)=> {
          // 异常断开：bNormalClose = false
          // JS_Disconnect正常断开：bNormalClose = true
          console.log("cbConnectClose");
          oWebControl = null;
          $("#playWnd").html("插件未启动，正在尝试启动，请稍候...");
          WebControl.JS_WakeUp("VideoWebPlugin://");
          initCount++;
          if (initCount < 3) {
            setTimeout(()=> {
              this.initPlugin();
            }, 3000)
          } else {
            $("#playWnd").html("插件启动失败，请检查插件是否安装！");
          }
        }
      });

    },
    init() {
      //param = {
      //
      //}
      let that = this

      let JsonParam = {
        "argument": '{"appkey": "20124682","ip": "172.139.0.194","port": 443,"secret": "vWF3o9ts58FzVswsejcH","enableHTTPS": 1,"language": "zh_CN","layout":"2x2","playMode": 0,"reconnectDuration": 5,"reconnectTimes": 5,"showSmart": 0,"showToolbar": 1,"snapDir": "D:/snap","videoDir": "D:/video"}',
        "funcName": "init"
      }

      console.log(22222,JsonParam)
      JsonParam.argument = JSON.parse(JsonParam.argument);
      JsonParam.argument.layout = this.show_type;
      JsonParam.argument = JSON.stringify(JsonParam.argument);

      oWebControl.JS_RequestInterface(JsonParam).then(function (oData) {
        console.log(11111,oData)
        console.log(JSON.stringify(oData ? oData.responseMsg : ''));
        oWebControl.JS_Resize(800, 400);  //
        that.requestInterface()
      });
    },
    // 设置窗口控制回调
    setCallbacks() {
      oWebControl.JS_SetWindowControlCallback({
        cbIntegrationCallBack: this.cbIntegrationCallBack
      });
    },

    // 推送消息
    cbIntegrationCallBack(oData) {
      console.log(JSON.stringify(oData.responseMsg));
    },

    // RSA加密
    setEncrypt(value) {
      var encrypt = new JSEncrypt();
      encrypt.setPublicKey(pubKey);
      return encrypt.encrypt(value);
    },

    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj=JSON.parse(str);
          if(typeof obj == 'object' && obj ){
            return true;
          }else{
            console.log("param is not the correct JSON message");
            return false;
          }
        } catch(e) {
          console.log("param is not the correct JSON message");
          return false;
        }
      }
      console.log('It is not a string!')
    },
    setWndCover() {
      //获取web页面的尺寸
      var iWidth = $(window).width();
      var iHeight = $(window).height();
      //获取播放窗口div元素的左边界、右边界距离web页面左边界的长度、上边界、下边界距离web页面上边界的长度
      var oDivRect = $("#playWnd").get(0).getBoundingClientRect();
      //Math.round 为四舍五入    Math.abs 为取绝对值
      var iCoverLeft = (oDivRect.left < 0) ? Math.abs(oDivRect.left): 0;
      var iCoverTop = (oDivRect.top < 0) ? Math.abs(oDivRect.top): 0;
      var iCoverRight = (oDivRect.right - iWidth > 0) ? Math.round(oDivRect.right - iWidth) : 0;
      var iCoverBottom = (oDivRect.bottom - iHeight > 0) ? Math.round(oDivRect.bottom - iHeight) : 0;

      iCoverLeft = (iCoverLeft > 800) ? 800 : iCoverLeft;
      iCoverTop = (iCoverTop > 400) ? 400 : iCoverTop;
      iCoverRight = (iCoverRight > 800) ? 800 : iCoverRight;
      iCoverBottom = (iCoverBottom > 400) ? 400 : iCoverBottom;

      oWebControl.JS_RepairPartWindow(0, 0, 801, 400);  // 多1个像素点防止还原后边界缺失一个像素条
      //抠除左边界
      if (iCoverLeft != 0) {
        oWebControl.JS_CuttingPartWindow(0, 0, iCoverLeft, 401);
      }
      //抠除上边界
      if (iCoverTop != 0) {
        oWebControl.JS_CuttingPartWindow(0, 0, 801, iCoverTop);  // 多剪掉一个像素条，防止出现剪掉一部分窗口后出现一个像素条
      }
      //抠除右边界
      if (iCoverRight != 0) {
        oWebControl.JS_CuttingPartWindow(801 - iCoverRight, 0, iCoverRight, 401);
      }
      //抠除下边界
      if (iCoverBottom != 0) {
        oWebControl.JS_CuttingPartWindow(0, 401 - iCoverBottom, 801, iCoverBottom);
      }
      //弹框示例位置扣除
      if (showDivInstruction)
      {
        // 获取弹框的位置、尺寸信息
        var oDivLightRect = document.getElementById('light').getBoundingClientRect();

        iCoverLeft = (oDivLightRect.left - oDivRect.left < 0) ? 0 : oDivLightRect.left - oDivRect.left;
        iCoverTop = (oDivLightRect.top - oDivRect.top < 0) ? 0 : oDivLightRect.top - oDivRect.top;
        iCoverRight = (oDivLightRect.right - oDivRect.left < 0) ? 0 : oDivLightRect.right - oDivRect.left;
        iCoverBottom = (oDivLightRect.bottom - oDivRect.top < 0) ? 0 : oDivLightRect.bottom - oDivRect.top;

        iCoverLeft = (iCoverLeft > 800) ? 800 : Math.round(iCoverLeft);
        iCoverTop = (iCoverTop > 400) ? 400 : Math.round(iCoverTop);
        iCoverRight = (iCoverRight > 800) ? 800 : Math.round(iCoverRight);
        iCoverBottom = (iCoverBottom > 400) ? 400 : Math.round(iCoverBottom);

        //JS_CuttingPartWindow接口参照开发指南，参数为：抠图左上角点在插件窗口上的left长度、top长度、所扣除矩形区域的宽度、所扣除矩形区域的长度
        oWebControl.JS_CuttingPartWindow(iCoverLeft - 1, iCoverTop - 1, iCoverRight - iCoverLeft + 2, iCoverBottom - iCoverTop + 2);
      }
    },
    dateFormat(oDate, fmt) {
      var o = {
        "M+": oDate.getMonth() + 1, //月份
        "d+": oDate.getDate(), //日
        "h+": oDate.getHours(), //小时
        "m+": oDate.getMinutes(), //分
        "s+": oDate.getSeconds(), //秒
        "q+": Math.floor((oDate.getMonth() + 3) / 3), //季度
        "S": oDate.getMilliseconds()//毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (oDate.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
      }
      return fmt;
    },
    //计算缩放比例
    adaptation() {
      var w = document.body.clientWidth;
      var h = document.body.clientHeight;
      var nw = 1920,
        nh = 1080;
      var left, top, scale;
      if (w / h > nw / nh) {
        scale = h / nh;
        top = 0;
        left = (w - nw * scale) / 2;
      } else {
        scale = w / nw;
        left = 0;
        top = (h - nh * scale) / 2;
      }
      document.getElementById('main').setAttribute('style', 'transform: scale(' + scale + ');' + 'top:' + top + 'px;');

    },
    getNav(item, index) {
      if (this.active == index) {
        return
      }
      this.active = index
      this.requestInterface(item.value)
    },

    // value为字符串，JS_RequestInterface仅接收json格式的变量，且需要先解析出argument，并且将argument字段的内容转为字符串
    requestInterface() {
      var JsonParam = {
        "argument": {
          "authUuid": "",
          "cameraIndexCode": this.indexCode,
          "ezvizDirect": 0,
          "gpuMode": 0,
          "streamMode": 0,
          "transMode": 1,
          "wndId": -1,
          "cascade": 1
        },
        "funcName": "startPreview"
      };
      var JsonArgument = JsonParam.argument;
      JsonParam.argument = JSON.stringify(JsonArgument);
      oWebControl.JS_RequestInterface(JsonParam).then(function (oData) {
        console.log(oData)
        console.log(JSON.stringify(oData ? oData.responseMsg : ''));
      });
    },
  },
}
</script>

<style scoped>
#main {
  width: 1920px;
  height: 1080px;
  transform-origin: center top 0px;
  position: relative;
  left: 50%;
  margin-left: -960px;
  overflow: hidden;
  background-color: #dddddd;
  display: flex;
  font-family: '黑体';
  box-sizing: border-box;
}

.left {
  height: 1040px;
  width: 250px;
  flex-shrink: 0;
  margin: 20px 0px 20px 15px;
  background-color: #fff;
}

.content {
  flex: 1;
  height: 1040px;
  box-sizing: border-box;
  margin: 20px 15px 20px;
  background-color: #fff;
}

.nav-list-box {
  padding: 10px;
}

.nav-list-item {
  height: 60px;
  line-height: 60px;
  box-sizing: border-box;
  padding: 0 10px;
  font-size: 18px;
  background-color: #cccccc;
  color: #000000;
  cursor: pointer;
  border-bottom: 1px solid #666666;
}

.nav-list-item:hover {
  background-color: #449de2;
}

.nav-list-item-active {
  background-color: #0090ff;
  color: #ffffff;
}

</style>
